/**
 * Created by wanende on 2017/7/3.
 */

// 当前table相关信息
var table = {
    //初始化表格对象
    tableIns: null,
    // 当前实例配置
    options: {},

};
(function ($) {
    $.extend({
        // 表格封装处理
        table: {
            // 初始化表格参数
            init: function(options) {
                var defaults = {
                    id: "simple-table",
                    cols: [[]],
                    page: true,
                    toolbar: false,  //开启头部工具栏右侧
                    width: 800,  //开启头部工具栏右侧
                    height: 700,  //开启头部工具栏右侧
                    defaultToolbar: [
                        //  {title:'导出', layEvent:'exportExcel',icon:'layui-icon-export'}
                        // ,{title:'下载模板', layEvent:'exportExcel',icon:'layui-icon-download-circle'}
                        // ,{title:'上传', layEvent:'exportExcel',icon:'layui-icon-upload'}
                    ], //头部工具栏右侧图标
                    full: false,
                };
                var formTable;

                var options = $.extend(defaults, options);

                table.options = options;

                var ti = {ti:new Date().getTime()};

                layui.use(['table'], function(){
                    var laytable = layui.table;

                    formTable = laytable.render({
                        elem: '#' + options.id,
                        url: options.url,
                        method: 'POST',
                        defaultToolbar: options.defaultToolbar,
                        toolbar: options.toolbar,
                        where:Object.assign(ti,options.where),
                        request: {
                            pageName: 'currentPage' //页码的参数名称，默认：page
                            ,limitName: 'showCount' //每页数据量的参数名，默认：limit
                        },
                        response: {
                            statusName: 'status' //数据状态的字段名称，默认：code
                            ,statusCode: true //成功的状态码，默认：0
                            ,msgName: 'msg' //状态信息的字段名称，默认：msg
                            ,countName: 'totalResult' //数据总数的字段名称，默认：count
                            ,dataName: 't' //数据列表的字段名称，默认：data
                        },
                        cols: options.cols,
                        page: options.page
                    });

                    table.tableIns = formTable;

                    laytable.on('tool(' + options.id + ')', function(obj){
                        var data = obj.data;
                        $.operate.getFn(obj.event,data);

                    });
                    laytable.on('toolbar(' + options.id + ')', function(obj){
                        var data = obj.data;
                        $.operate.getFn(obj.event,data);
                    });
                });
            },

            // 搜索-默认第一个form
            search: function(formId) {

                var currentId = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                var dataParam = $("#" + currentId).serializeJSON();

                var ti = {ti:new Date().getTime()};
                table.tableIns.reload({
                    where: Object.assign(Object.assign(ti,options.where),dataParam)
                    ,page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
            },
            delFlag: function(data) {
                data = eval(data);
                layer.confirm('真的删除<span style="color: #9f191f"></span>吗?', function(index){
                    var javaField = table.options.javaField;
                    var field = $.common.getField(data,javaField);

                    var dataParam = {};
                    dataParam[javaField] = field;

                    $.operate.post(table.options.deleteUrl, dataParam, function(result) {
                        if (result.status == true) {
                            layer.close(index);
                            $.table.search();
                        } else {
                            layer.alert(data.msg);
                        }
                    });
                });
            },
            addFlag: function(data) {
                $.modal.open(table.options.modalName, table.options.addUrl, table.options.width, table.options.height, table.options.editFull,null);
            },
            editFlag: function(data) {
                var javaField = table.options.javaField;
                var field = $.common.getField(data,javaField);
                $.modal.open(table.options.modalName, table.options.editUrl + field, table.options.width, table.options.height, table.options.editFull,null);
            },
            // 导出数据
            exportExcel: function(formId) {
                $.modal.confirm("确定导出所有" + table.options.modalName + "吗？", function() {
                    var currentId = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                    var dataParam = $("#" + currentId).serializeJSON();
                    $.operate.post(table.options.exportUrl, dataParam, function(result) {
                        if (result.status == true) {
                            window.location.href = basePath + "common/download?fileName=" + encodeURI(result.t) + "&delete=" + true;
                        } else {
                            layer.alert(result.msg);
                        }
                    });
                });
            },
            // 下载模板
            importTemplate: function() {
                $.get(table.options.importTemplateUrl, function(result) {
                    if (result.status == true) {
                        window.location.href = basePath + "common/download?fileName=" + encodeURI(result.msg) + "&delete=" + true;
                    } else {
                        layer.alert(result.msg);
                    }
                });
            },
            // 导入数据
            importExcel: function(formId) {
                table.set();
                var currentId = $.common.isEmpty(formId) ? 'importTpl' : formId;
                layer.open({
                    type: 1,
                    area: ['400px', '230px'],
                    fix: false,
                    //不固定
                    maxmin: true,
                    shade: 0.3,
                    title: '导入' + table.options.modalName + '数据',
                    content: $('#' + currentId).html(),
                    btn: ['<i class="fa fa-check"></i> 导入', '<i class="fa fa-remove"></i> 取消'],
                    // 弹层外区域关闭
                    shadeClose: true,
                    btn1: function(index, layero){
                        var file = layero.find('#file').val();
                        if (file == '' || (!$.common.endWith(file, '.xls') && !$.common.endWith(file, '.xlsx'))){
                            $.modal.msgWarning("请选择后缀为 “xls”或“xlsx”的文件。");
                            return false;
                        }
                        var index = layer.load(2, {shade: false});
                        $.modal.disable();
                        var formData = new FormData(layero.find('form')[0]);
                        $.ajax({
                            url: table.options.importUrl,
                            data: formData,
                            cache: false,
                            contentType: false,
                            processData: false,
                            type: 'POST',
                            success: function (result) {
                                if (result.code == web_status.SUCCESS) {
                                    $.modal.closeAll();
                                    $.modal.alertSuccess(result.msg);
                                    $.table.refresh();
                                } else if (result.code == web_status.WARNING) {
                                    layer.close(index);
                                    $.modal.enable();
                                    $.modal.alertWarning(result.msg)
                                } else {
                                    layer.close(index);
                                    $.modal.enable();
                                    $.modal.alertError(result.msg);
                                }
                            }
                        });
                    }
                });
            },



        },


        // 弹出层封装处理
        modal: {
            // 成功消息
            msgSuccess: function(content) {
                $.modal.msg(content, modal_status.SUCCESS);
            },
            // 警告消息
            msgWarning: function(content) {
                $.modal.msg(content, modal_status.WARNING);
            },
            // 弹出提示
            alert: function(content, type) {
                layer.alert(content, {
                    icon: $.modal.icon(type),
                    title: "系统提示",
                    btn: ['确认'],
                    btnclass: ['btn btn-primary'],
                });
            },
            // 消息提示并刷新父窗体
            msgReload: function(msg, type) {
                layer.msg(msg, {
                        icon: $.modal.icon(type),
                        time: 500,
                        shade: [0.1, '#8F8F8F']
                    },
                    function() {
                        $.modal.reload();
                    });
            },
            // 错误提示
            alertError: function(content) {
                $.modal.alert(content, modal_status.FAIL);
            },
            // 成功提示
            alertSuccess: function(content) {
                $.modal.alert(content, modal_status.SUCCESS);
            },
            // 警告提示
            alertWarning: function(content) {
                $.modal.alert(content, modal_status.WARNING);
            },
            // 关闭窗体
            close: function () {
                var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);
            },
            // 关闭全部窗体
            closeAll: function () {
                layer.closeAll();
            },
            // 确认窗体
            confirm: function (content, callBack) {
                layer.confirm(content, {
                    icon: 3,
                    title: "系统提示",
                    btn: ['确认', '取消']
                }, function (index) {
                    layer.close(index);
                    callBack(true);
                });
            },

            /**
             * @param title 标题
             * @param url   打开地址
             * @param width 弹出框宽
             * @param height    弹出框高
             * @param full  全屏 默认false
             * @param callback  确定后回调函数 默认 submitHandler
             */
            open: function (title, url, width, height,full, callback) {
                //如果是移动端，就使用自适应大小弹窗
                if ($.common.isMobile()) {
                    width = 'auto';
                    height = 'auto';
                }
                if ($.common.isEmpty(title)) {
                    title = false;
                }
                if ($.common.isEmpty(url)) {
                    url = "/404.html";
                }
                if ($.common.isEmpty(width)) {
                    width = 800;
                }
                if ($.common.isEmpty(height)) {
                    height = ($(window).height() - 50);
                }
                if ($.common.isEmpty(full)) {
                    full = false;
                }
                if ($.common.isEmpty(callback)) {
                    callback = function(index, layero) {
                        var iframeWin = layero.find('iframe')[0];
                        iframeWin.contentWindow.submitHandler(index, layero);
                    }
                }
                var index = layer.open({
                    type: 2,
                    area: [width + 'px', height + 'px'],
                    fix: false,
                    //不固定
                    maxmin: true,
                    shade: 0.3,
                    title: title,
                    content: url,
                    btn: ['确定', '关闭'],
                    // 弹层外区域关闭
                    shadeClose: true,
                    yes: callback,
                    no: function (index) {
                        layer.close(index);
                    },
                    end: function () {
                        $.table.search();
                    }
                });
                if(full){
                    layer.full(index);
                }
            },
            // 弹出层指定参数选项
            openOptions: function (options) {
                var _url = $.common.isEmpty(options.url) ? "/404.html" : options.url;
                var _title = $.common.isEmpty(options.title) ? "系统窗口" : options.title;
                var _width = $.common.isEmpty(options.width) ? "800" : options.width;
                var _height = $.common.isEmpty(options.height) ? ($(window).height() - 50) : options.height;
                var _btn = ['<i class="fa fa-check"></i> 确认', '<i class="fa fa-close"></i> 关闭'];
                if ($.common.isEmpty(options.yes)) {
                    options.yes = function(index, layero) {
                        options.callBack(index, layero);
                    }
                }
                layer.open({
                    type: 2,
                    maxmin: true,
                    shade: 0.3,
                    title: _title,
                    fix: false,
                    area: [_width + 'px', _height + 'px'],
                    content: _url,
                    shadeClose: $.common.isEmpty(options.shadeClose) ? true : options.shadeClose,
                    skin: options.skin,
                    btn: $.common.isEmpty(options.btn) ? _btn : options.btn,
                    yes: options.yes,
                    cancel: function () {
                        return true;
                    }
                });
            },
            // 禁用按钮
            disable: function() {
                var doc = window.top == window.parent ? window.document : window.parent.document;
                $("a[class*=layui-layer-btn]", doc).addClass("layer-disabled");
            },
            // 启用按钮
            enable: function() {
                var doc = window.top == window.parent ? window.document : window.parent.document;
                $("a[class*=layui-layer-btn]", doc).removeClass("layer-disabled");
            },
            // 打开遮罩层
            loading: function (message) {
                $.blockUI({ message: '<div class="loaderbox"><div class="loading-activity"></div> ' + message + '</div>' });
            },
            // 关闭遮罩层
            closeLoading: function () {
                setTimeout(function(){
                    $.unblockUI();
                }, 50);
            },
            // 重新加载
            reload: function () {
                parent.location.reload();
            }
        },
        // 操作封装处理
        operate: {
            // 提交数据
            submit: function(url, type, dataType, data, callback) {
                var config = {
                    url: url,
                    type: type,
                    dataType: dataType,
                    data: data,
                    beforeSend: function () {
                        this.layerIndex = layer.load("加载中...",{shade:[0.5,'#393d49'],content:'<br><p style="white-space: nowrap">数据正在加载中,请耐心等待...</p>'});
                    },
                    success: function(result) {
                        if (typeof callback == "function") {
                            callback(result);
                        }else{

                        }
                        layer.close(this.layerIndex);
                    },
                    error: function () {
                        layer.close(this.layerIndex);
                        layer.msg("数据加载失败！")
                    }
                };
                $.ajax(config)
            },
            // post请求传输
            post: function(url, data, callback) {
                $.operate.submit(url, "post", "json", data, callback);
            },
            // get请求传输
            get: function(url,data, callback) {
                $.operate.submit(url, "get", "json", data, callback);
            },


            // 保存结果弹出msg刷新table表格
            ajaxSuccess: function (result) {
                if (result.code == web_status.SUCCESS && table.options.type == table_type.bootstrapTable) {
                    $.modal.msgSuccess(result.msg);
                    $.table.refresh();
                } else if (result.code == web_status.SUCCESS && table.options.type == table_type.bootstrapTreeTable) {
                    $.modal.msgSuccess(result.msg);
                    $.treeTable.refresh();
                } else if (result.code == web_status.SUCCESS && table.option.type == undefined) {
                    $.modal.msgSuccess(result.msg)
                }  else if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.msg)
                }  else {
                    $.modal.alertError(result.msg);
                }
                $.modal.closeLoading();
            },

            // 选项卡成功回调执行事件（父窗体静默更新）
            getFn: function(fn,data) {
                //
                // try{
                //     var ty = eval('$.table.'+ fn + '('+JSON.stringify(data)+')');
                //     if(typeof (ty) == "undefined" || typeof (ty) == 'function'){
                //         return true;
                //     }else {
                //         var ty = eval(fn + '('+JSON.stringify(data)+')');
                //     }
                // }catch (e) {
                // }
                //
                if($.common.isFunction('$.table.'+ fn + '('+JSON.stringify(data)+')')){
                    // eval('$.table.'+ fn + '('+JSON.stringify(data)+')');
                    return true;
                }else if($.common.isFunction(fn + '('+JSON.stringify(data)+')')){
                    // eval( fn + '('+JSON.stringify(data)+')');
                    return true;
                }else{
                    layer.alert('没有找打方法：'+ fn);
                    return true;
                }


                //window['$.operate.'+ fn]();
            }

        },

        // 通用方法封装处理
        common: {
            isFunction: function(funcName){
                try{
                    var ty = eval(funcName);
                    if(typeof (ty) == "undefined" || typeof (ty) == 'function'){
                        return true;
                    }
                }catch (e) {
                }
                return false;
            },
            getField: function(data,fields,pattern){
                var arr = fields.split('.');
                var key = arr.shift();
                var value = data[key];
                if(value==null){
                    return value;
                }else if(arr.length==0){
                    if(!pattern)return value;
                    var type = Object.prototype.toString.call(value).replace('[object ','').replace(']','');
                    if(pattern===true){
                        return type;
                    }else if(!pattern){
                        return value;
                    }else{
                        return type==pattern;
                    }
                }
                var result = getField(value,arr.join('.'),pattern);
                return result;
            },
            // 判断字符串是否为空
            isEmpty: function (value) {
                if (value == null || this.trim(value) == "") {
                    return true;
                }
                return false;
            },
            // 判断一个字符串是否为非空串
            isNotEmpty: function (value) {
                return !$.common.isEmpty(value);
            },
            // 空对象转字符串
            nullToStr: function(value) {
                if ($.common.isEmpty(value)) {
                    return "-";
                }
                return value;
            },
            // 是否显示数据 为空默认为显示
            visible: function (value) {
                if ($.common.isEmpty(value) || value == true) {
                    return true;
                }
                return false;
            },
            // 空格截取
            trim: function (value) {
                if (value == null) {
                    return "";
                }
                return value.toString().replace(/(^\s*)|(\s*$)|\r|\n/g, "");
            },
            // 比较两个字符串（大小写敏感）
            equals: function (str, that) {
                return str == that;
            },
            // 比较两个字符串（大小写不敏感）
            equalsIgnoreCase: function (str, that) {
                return String(str).toUpperCase() === String(that).toUpperCase();
            },
            // 将字符串按指定字符分割
            split: function (str, sep, maxLen) {
                if ($.common.isEmpty(str)) {
                    return null;
                }
                var value = String(str).split(sep);
                return maxLen ? value.slice(0, maxLen - 1) : value;
            },
            // 字符串格式化(%s )
            sprintf: function (str) {
                var args = arguments, flag = true, i = 1;
                str = str.replace(/%s/g, function () {
                    var arg = args[i++];
                    if (typeof arg === 'undefined') {
                        flag = false;
                        return '';
                    }
                    return arg;
                });
                return flag ? str : '';
            },
            // 指定随机数返回
            random: function (min, max) {
                return Math.floor((Math.random() * max) + min);
            },
            // 判断字符串是否是以start开头
            startWith: function(value, start) {
                var reg = new RegExp("^" + start);
                return reg.test(value)
            },
            // 判断字符串是否是以end结尾
            endWith: function(value, end) {
                var reg = new RegExp(end + "$");
                return reg.test(value)
            },
            // 数组去重
            uniqueFn: function(array) {
                var result = [];
                var hashObj = {};
                for (var i = 0; i < array.length; i++) {
                    if (!hashObj[array[i]]) {
                        hashObj[array[i]] = true;
                        result.push(array[i]);
                    }
                }
                return result;
            },
            // 数组中的所有元素放入一个字符串
            join: function(array, separator) {
                if ($.common.isEmpty(array)) {
                    return null;
                }
                return array.join(separator);
            },
            // 获取form下所有的字段并转换为json对象
            formToJSON: function(formId) {
                var json = {};
                $.each($("#" + formId).serializeArray(), function(i, field) {
                    if(json[field.name]) {
                        json[field.name] += ("," + field.value);
                    } else {
                        json[field.name] = field.value;
                    }
                });
                return json;
            },
            // 获取obj对象长度
            getLength: function(obj) {
                var count = 0;
                for (var i in obj) {
                    if (obj.hasOwnProperty(i)) {
                        count++;
                    }
                }
                return count;
            },
            // 判断移动端
            isMobile: function () {
                return navigator.userAgent.match(/(Android|iPhone|SymbianOS|Windows Phone|iPad|iPod)/i);
            },
        }
    });
})(jQuery);



function loadPage(url,accessMode) {
    if(url == "" || url == null){
        return;
    }
    var  res = basePath+url;
    $("#iframeContent").empty();


    if("iframe" == accessMode){
        $("#iframeContent").append('<iframe name="mainFrame" id="mainFrame"  src="'+url+'" frameborder="0" style="margin:0 auto;width:99%;min-height:95% ;border:none;background:#fff;position: absolute;">');
        return;
    }

    if(res.indexOf('?') == -1){
        res = res+"?datetime="+new Date().getTime();
    }else{
        res = res+"&datetime="+new Date().getTime();
    }
    $("#iframeContent").load(res,function(data){
        //回调函数里面的内容
        if(data == ""){
            location.reload();
        }else{
            if(data.indexOf("loginForm") != -1){
                window.location.href = basePath + "login_toLogin";
            }
            if(data.indexOf("div") == -1){
                data = eval("["+data+"]")[0];
                if(data.status == false){
                    $("#iframeContent").empty();
                    $("#iframeContent").load(basePath+"500",{"exception":data.msg})
                }
            }
        }
    });
}
